package com.jstreams.utils;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

public class ByteToCharUtils {

	/**
	 * InputStream 转换为 InputStreamReader
	 * 
	 * @param in
	 * @param charsetName
	 *            非必填，错误的会自动用UTF-8处理
	 * @return
	 */
	public static InputStreamReader getInputStreamReader(InputStream in, String charsetName) {
		if (!StringUtils.isNotEmpty(charsetName)) {
			return new InputStreamReader(in);
		}
		InputStreamReader isr = null;
		try {
			isr = new InputStreamReader(in, charsetName);
		} catch (UnsupportedEncodingException e) {
			try {
				isr = new InputStreamReader(in, "UTF-8");
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
		return isr;
	}

	/**
	 * OutputStream 转换为 OutputStreamWriter
	 * 
	 * @param out
	 * @param charsetName
	 *            非必填，错误的会自动用UTF-8处理
	 * @return
	 */
	public static OutputStreamWriter getOutputStreamWriter(OutputStream out, String charsetName) {
		if (!StringUtils.isNotEmpty(charsetName)) {
			return new OutputStreamWriter(out);
		}
		OutputStreamWriter osw = null;
		try {
			osw = new OutputStreamWriter(out, charsetName);
		} catch (UnsupportedEncodingException e) {
			try {
				osw = new OutputStreamWriter(out, "UTF-8");
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
		return osw;
	}

}
